/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/most-frequent-subtree-sum
   @Language: C++
   @Datetime: 19-05-15 17:06
   */

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
	int postorder(TreeNode *root, unordered_map<int,int> &freq, int &maxfreq){
		if(root==NULL) return 0;
		int left=postorder(root->left,freq,maxfreq);
		int right=postorder(root->right,freq,maxfreq);
		root->val+=left+right;
		++freq[root->val];
		maxfreq=max(maxfreq,freq[root->val]);
		return root->val;
	}
public:
	/**
	 * @param root: the root
	 * @return: all the values with the highest frequency in any order
	 */
	vector<int> findFrequentTreeSum(TreeNode * root) {
		// Write your code here
		unordered_map<int,int> freq;
		int maxfreq=0;
		postorder(root,freq,maxfreq);
		vector<int> v;
		for(const auto &p:freq)
			if(p.second!=maxfreq) continue;
			else v.push_back(p.first);
		return v;
	}
};
